package com.linefly.online_car;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.linefly.online_car.Custom.MyLoading;
import com.linefly.online_car.Custom.ReLogin;
import com.linefly.online_car.popwindow.BottomPopupOption;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import Adapter.Adapter_chooselogo;
import Been.Carsbeen;
import Util.JsonUtil;
import Util.NavigationBarUtil;
import Util.PreferenceUtil;
import Util.ToastUtil;
import okhttp3.Call;
import okhttp3.Response;

public class Choose_Logo extends AppCompatActivity {
    String token_Str;
    ArrayList arrayList;
    String id_store_origin,id_store_terminus,time_origin,time_terminus;
    RecyclerView recyclerView;
    List<String> list;
    Adapter_chooselogo adapter_chexingxuanze;
    private HashMap hashMap_detail;//用户信息的表
    View nodata;
    private BottomPopupOption bottomPopupOption;
    private int REQUEST_TAKE_PHOTO_PERMISSION = 1;
    private  String IMAGE_FILE_NAME ;

    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose__logo);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //   getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }
        if(NavigationBarUtil.hasNavigationBar(this)){
            NavigationBarUtil.initActivity(findViewById(android.R.id.content));//解决底部适配
        }
        //获取当前登录状态

        token_Str = PreferenceUtil.getString("token", "");

        nodata = (View)findViewById(R.id.nodata);
        IMAGE_FILE_NAME = getPhotoFileName();



        recyclerView = (RecyclerView)findViewById(R.id.recycler);
        list =new ArrayList<>();
        arrayList = new ArrayList();
        init();

    }

    public void init(){
        MyLoading.show(this);
        try {
            String url = getString(R.string.url) + "/device/logos";

            OkHttpUtils.get(url)
                    .connTimeOut(10000)
                    .params("token",token_Str)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if(object instanceof HashMap) {
                                final HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {

                                    arrayList = (ArrayList)hashMap.get("list");
                                    list = arrayList;
                                    list.set(0,"");
                                    if(list.size() == 0){
                                        nodata.setVisibility(View.GONE);
                                    }

                                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(Choose_Logo.this);
                                    adapter_chexingxuanze = new Adapter_chooselogo(list);
                                    recyclerView.setLayoutManager(linearLayoutManager);
                                    recyclerView.setAdapter(adapter_chexingxuanze);
                                    adapter_chexingxuanze.setItemClick(new Adapter_chooselogo.item_click() {
                                        @Override
                                        public void itemclick(int position) {
                                            if(position == 0){
                                                //选择图片
                                                if(ContextCompat.checkSelfPermission(Choose_Logo.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                                        != PackageManager.PERMISSION_GRANTED){
                                                    ActivityCompat.requestPermissions(Choose_Logo.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10000);
                                                }

                                                bottomPopupOption = new BottomPopupOption(Choose_Logo.this);
                                                bottomPopupOption.setItemText("拍照","相册");
                                                bottomPopupOption.showPopupWindow();
                                                bottomPopupOption.setItemClickListener(new BottomPopupOption.onPopupWindowItemClickListener() {
                                                    @Override
                                                    public void onItemClick(int position) {
                                                        bottomPopupOption.dismiss();
                                                        switch (position){
                                                            case 0:
                                                                //      Toast.makeText(Choose_Logo.this,"拍照",Toast.LENGTH_SHORT).show();

                                                                //      choseHeadImageFromCameraCapture();
                                                                photograph();

                                                                break;
                                                            case 1:
                                                                //    Toast.makeText(Choose_Logo.this,"相册",Toast.LENGTH_SHORT).show();


                                                                //    choseHeadImageFromGallery();
                                                                photoalbum();

                                                                break;
                                                        }
                                                    }
                                                });
                                            }else {
                                                EventBus.getDefault().post(new Carsbeen(list.get(position),1000,999.0,999.0,1,1));
                                                finish();
                                            }



                                        }
                                    });


                                }else if(err < 0){
                                    ReLogin.login(Choose_Logo.this);
                                }else {
                                    Toast.makeText(Choose_Logo.this,hashMap.get("msg").toString(),Toast.LENGTH_LONG).show();
                                }
                            }


                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            MyLoading.cancel();
                            Toast.makeText(Choose_Logo.this, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });

        }catch (Exception e) {
            MyLoading.cancel();
            e.printStackTrace();
        }



    }


public void click_back(View view){
        finish();
}

    //调用拍照和相册的函数
    //用当前时间给取得的图片命名
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyy-MM-dd_HH:mm:ss");
        return dateFormat.format(date) + ".jpg";
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {

        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
//            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }

        switch (requestCode) {

            case PictureConfig.CHOOSE_REQUEST:
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(intent);
                for (LocalMedia media : selectList) {
                    Log.e("photo cut-->", media.getCutPath());
                    setImageToHeadView(media.getCutPath());
                }
                break;

        }

        super.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_TAKE_PHOTO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //申请成功，可以拍照
                choseHeadImageFromCameraCapture();
            } else {
                Toast.makeText(Choose_Logo.this,"你拒绝了权限，该功能不可用\n可在应用设置里授权拍照哦",Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    // 启动手机相机拍摄照片作为头像
    private void choseHeadImageFromCameraCapture() {
        //6.0以上动态获取权限
        if (ContextCompat.checkSelfPermission(Choose_Logo.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请权限，REQUEST_TAKE_PHOTO_PERMISSION是自定义的常量
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    REQUEST_TAKE_PHOTO_PERMISSION);

        } else {
            Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            // 判断存储卡是否可用，存储照片文件
            if (hasSdcard()) {

                intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                        .fromFile(new File(Environment
                                .getExternalStorageDirectory(), IMAGE_FILE_NAME)));
            }
            startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);
        }

    }
    /**
     * 提取保存裁剪之后的图片数据，并设置头像部分的View
     */
    private void setImageToHeadView(String path) {

        File file = new File(path);
        if (!file.exists()) {
            Toast.makeText(Choose_Logo.this, "文件不存在", Toast.LENGTH_SHORT).show();
        }
        MyLoading.show(this);
        //  访问网络
        try {
            String url = getString(R.string.url) + "/upload?token=" + token_Str;
            OkHttpUtils.post(url)
                    .connTimeOut(10000)
                    .params("", file)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if (object instanceof HashMap) {
                                HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {
                                    HashMap hashMap1 = (HashMap) hashMap.get("result");
                                    String url = hashMap1.get("url").toString();
                                    EventBus.getDefault().post(new Carsbeen(url,1000,999.0,999.0,1,1));
                                    finish();
                                    //Toast.makeText(Choose_Logo.this,"上传成功"+url,Toast.LENGTH_LONG).show();



                                }else if(err < 0){
                                    MyLoading.cancel();
                                    ReLogin.login(Choose_Logo.this);
                                }else {
                                    MyLoading.cancel();
                                    ToastUtil.toast(Choose_Logo.this,hashMap.get("msg").toString());
                                }

                            }

                        }
                    });
        } catch (Exception e) {
            MyLoading.cancel();
            Toast.makeText(Choose_Logo.this, "连接服务器失败", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 有存储的SDCard
            return true;
        } else {
            return false;
        }
    }

    /**
     * 拍照
     */
    public void photograph() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .theme(R.style.picture_white_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(false)
                .previewVideo(false)
                .enablePreviewAudio(false)
                .isCamera(false)
                .enableCrop(true)
                .compress(false)
                .glideOverride(160, 160)
                .withAspectRatio(1, 1)
                .hideBottomControls(true)
                .isGif(false)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .previewEggs(false)
                .minimumCompressSize(100)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 相册
     */
    public void photoalbum() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_white_style)
                .maxSelectNum(2)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .previewVideo(false)
                .enablePreviewAudio(false)
                .isCamera(false)
                .isZoomAnim(true)
                .enableCrop(true)
                .compress(false)
                .synOrAsy(true)
                .glideOverride(160, 160)
                .withAspectRatio(1, 1)
                .hideBottomControls(true)
                .isGif(false)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .minimumCompressSize(100)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

}
